package com.financing.platform.service.impl;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.financing.platform.common.BizEnums;
import com.financing.platform.dao.IPaymentDao;
import com.financing.platform.dao.IProjectDao;
import com.financing.platform.dto.FpBiddingReceiptDTO;
import com.financing.platform.dto.FpPaymentDTO;
import com.financing.platform.dto.OrderByGaiZaoDTO;
import com.financing.platform.dto.OrderDTO;
import com.financing.platform.dto.ProjectDTO;
import com.financing.platform.service.IFpBiddingReceiptService;
import com.financing.platform.service.IOrderService;
import com.financing.platform.service.IPaymentService;
import com.financing.platform.util.StringUtil;

@Service("paymentServiceImpl")
public class PaymentServiceImpl implements IPaymentService{

	@Autowired
	private IPaymentDao paymentDaoImpl;
	
	@Autowired
	private IFpBiddingReceiptService fpBiddingReceiptService;
	
	@Autowired
	private IOrderService orderServiceImpl;
	
	@Autowired
	private IProjectDao projectDaoImpl;
	
	Logger logger = Logger.getLogger(getClass());
	
	private SimpleDateFormat sd = new SimpleDateFormat(
			BizEnums.CommonEnums.JUYOUBAO_DATE_PATTERN);// 聚友投平台日期格式
	
	@Override
	public int insertPayment(FpPaymentDTO paymentDTO) throws SQLException {
		return paymentDaoImpl.insertPayment(paymentDTO);
	}

	@Override
	public FpPaymentDTO loadByOrderId(Map<String,String> map) throws SQLException {
		return paymentDaoImpl.loadByOrderId(map);
	}

	@Override
	public void updatePayment(FpPaymentDTO paymentUp) throws SQLException{
		
		 paymentDaoImpl.updatePayment(paymentUp);
	}

	@Override
	public List<FpPaymentDTO> queryPaymentList(FpPaymentDTO paymentUp)
			throws SQLException {
		return paymentDaoImpl.queryPaymentList(paymentUp);
	}

	@Override
	public int queryPaymentListCount(FpPaymentDTO paymentDTO)
			throws SQLException {
		return paymentDaoImpl.queryPaymentListCount(paymentDTO);
	}

	@Override
	public List<FpPaymentDTO> loadByAmountDetail(String associationId,String amountType) throws SQLException {
		
		String orderId = "";
		
		//01 保证金 02 佣金
		if("01".equals(amountType)){
			FpBiddingReceiptDTO dto = new FpBiddingReceiptDTO();
			dto.setId(Integer.parseInt(associationId));
			dto = fpBiddingReceiptService.queryBiddingReceipt(dto);
			
			orderId = (dto==null?"":dto.getBiddingCode());
		}else if("02".equals(amountType)){
			OrderDTO orderDTO = new OrderDTO();
			orderDTO.setId(associationId);
			orderDTO = orderServiceImpl.queryOrderDetail(orderDTO);
			
			orderId = (orderDTO==null?"":orderDTO.getoCode());
		}
		FpPaymentDTO paymentUp = new FpPaymentDTO();
		paymentUp.setOrderId(orderId);
		return paymentDaoImpl.queryPaymentList(paymentUp);
	}

	@Override
	public void updateByAmountDetail(String platSerialNo,FpPaymentDTO paymentDTO) throws SQLException {

		Map<String,String> map = new HashMap<String, String>();
		map.put("platSerialNo", platSerialNo.toString());
		FpPaymentDTO bean =  paymentDaoImpl.loadByOrderId(map);
		paymentDTO.setId(bean.getId());
		paymentDaoImpl.updatePayment(paymentDTO);
	}
	
	
	/**
	 * 订单后端线下提现
	 * @param orderDTO
	 * @throws SQLException
	 */
	@Override
	public void addPaymentForOrderBackRebate(OrderByGaiZaoDTO orderDTO,OrderByGaiZaoDTO orderTmp, String paymentStatus) throws SQLException {
		
		logger.info("begin addPaymentForOrderBackRebate #######################################订单后端线下提现:");
		
		String payPlat = "baofoo";
		String amountType = "txyj";
		Date now = new Date();
		
		logger.info("orderDTO.getoCode():"+orderTmp.getoCode());
		logger.info("orderDTO.getoFinanceBackRebate():"+orderDTO.getoFinanceBackRebate());
		logger.info("orderDTO.getoBackRebateBankCardNumber():"+orderDTO.getoBackRebateBankCardNumber());
		logger.info("orderDTO.getoBackRebateBankCardNumber():"+orderDTO.getoBackRebateBankCardNumber());
		logger.info("orderDTO.getoBackRebateBankId():"+orderDTO.getoBackRebateBankId());
		
		//获取产品名称
		ProjectDTO projectDTO = new ProjectDTO();
		projectDTO.setId(orderTmp.getoProjectId());
		projectDTO = projectDaoImpl.searchProjectByIdOrCode(projectDTO);
		String amountTypeName = projectDTO.getpName();
		
		FpPaymentDTO payment = new FpPaymentDTO();
		payment.setPayId(orderTmp.getoCode());//每笔订单一个支付流水，因此可重用ID
		payment.setPlatSerialNo(StringUtil.genPlatSerialNoSimple(
				payPlat));//平台流水号(加上支付商标识)
		payment.setOrderId(orderTmp.getoCode());//订单编码
		payment.setInterfaceType(amountType);//支付
		payment.setPayDate(sd.format(now));//支付日期
		payment.setPayStartTime(now);
		payment.setPayAmt(orderDTO.getoFinanceBackRebate());//支付金额 = 提现总金额
		payment.setCurCode(BizEnums.CommonEnums.MONEY_TYPE_RMB);//默认人民币
		payment.setOutAccount(BizEnums.CommonEnums.SUPERFA_FUND_ACCOUNT_NO);//资金存入账户 （超级理财师指定账户）
		payment.setInAccount(orderDTO.getoBackRebateBankCardNumber());//资金扣出账户（用户个人账户）
		payment.setPayStatus(paymentStatus);//支付状态
		payment.setTpay3plat(payPlat);//支付商标识
		payment.setPayDesc(amountTypeName);//支付描述
		payment.setCardCarrier(orderDTO.getoBackRebateBankCardHolder());//持卡人姓名
		payment.setUserId(orderTmp.getoFAId());//用户id
		payment.setCardNo(orderDTO.getoBackRebateBankCardNumber());//持卡号
		payment.setPayMode(orderDTO.getoBackRebateBankId());//交易方式
		payment.setPayType("offline");//支付类型（online,offline）
		payment.setUpdateBy(orderDTO.getUpdateBy());
		payment.setUpdateDate(new Date(System.currentTimeMillis()));
		payment.setCreateBy(orderDTO.getUpdateBy());
		payment.setCreateDate(new Date(System.currentTimeMillis()));
		payment.setPayEndTime(now);
		paymentDaoImpl.addPayment(payment);
		logger.info("end addPaymentForOrderBackRebate #######################################订单后端线下提现:");
	}
	/**
	 * 订单前端线下提现
	 * @param orderDTO
	 * @throws SQLException
	 */
	@Override
	public void addPaymentForOrderRebate(OrderByGaiZaoDTO orderDTO,OrderByGaiZaoDTO orderTmp, String paymentStatus) throws SQLException {
		logger.info("begin addPaymentForOrderRebate #######################################订单前端线下提现:");
		
		
		String payPlat = "baofoo";
		String amountType = "txyj";
		Date now = new Date();
		BigDecimal payAmt = null;
		payAmt = (orderDTO.getoFinanceFrontRebate()==null?new BigDecimal(0):orderDTO.getoFinanceFrontRebate())
				.add(orderDTO.getoActivityAmount()==null?new BigDecimal(0):orderDTO.getoActivityAmount())
				.add(orderDTO.getoFinanceOtherAmount()==null?new BigDecimal(0):orderDTO.getoFinanceOtherAmount());
		//获取产品名称
		ProjectDTO projectDTO = new ProjectDTO();
		projectDTO.setId(orderTmp.getoProjectId());
		projectDTO = projectDaoImpl.searchProjectByIdOrCode(projectDTO);
		String amountTypeName = projectDTO.getpName();
		
		logger.info("orderDTO.getoCode():"+orderTmp.getoCode());
		logger.info("payAmt:"+payAmt);
		logger.info("orderDTO.getoRebateBankCardNumber():"+orderDTO.getoRebateBankCardNumber());
		logger.info("orderDTO.getoRebateBankCardHolder():"+orderDTO.getoRebateBankCardHolder());
		logger.info("orderDTO.getoRebateBankId():"+orderDTO.getoRebateBankId());
				
		FpPaymentDTO payment = new FpPaymentDTO();
		payment.setPayId(orderTmp.getoCode());//每笔订单一个支付流水，因此可重用ID
		payment.setPlatSerialNo(StringUtil.genPlatSerialNoSimple(
				payPlat));//平台流水号(加上支付商标识)
		payment.setOrderId(orderTmp.getoCode());//订单编码
		payment.setInterfaceType(amountType);//支付
		payment.setPayDate(sd.format(now));//支付日期
		payment.setPayStartTime(now);
		payment.setPayAmt(payAmt);//支付金额 = 提现总金额
		payment.setCurCode(BizEnums.CommonEnums.MONEY_TYPE_RMB);//默认人民币
		payment.setOutAccount(BizEnums.CommonEnums.SUPERFA_FUND_ACCOUNT_NO);//资金存入账户 （超级理财师指定账户）
		payment.setInAccount(orderDTO.getoRebateBankCardNumber());//资金扣出账户（用户个人账户）
		payment.setPayStatus(paymentStatus);//支付状态
		payment.setTpay3plat(payPlat);//支付商标识
		payment.setPayDesc(amountTypeName);//支付描述
		payment.setCardCarrier(orderDTO.getoRebateBankCardHolder());//持卡人姓名
		payment.setUserId(orderTmp.getoFAId());//用户id
		payment.setCardNo(orderDTO.getoRebateBankCardNumber());//持卡号
		payment.setPayMode(orderDTO.getoRebateBankId());//交易方式
		payment.setPayType("offline");//支付类型（online,offline）
		payment.setUpdateBy(orderDTO.getUpdateBy());
		payment.setUpdateDate(new Date(System.currentTimeMillis()));
		payment.setCreateBy(orderDTO.getUpdateBy());
		payment.setCreateDate(new Date(System.currentTimeMillis()));
		payment.setPayEndTime(now);
		paymentDaoImpl.addPayment(payment);

	}
}
